package com.template.ejb.service.util;

import java.util.Map;

import javax.naming.InitialContext;

import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;

/**
 * 
 * 
 */
public class JbpmEngine {

	private static JbpmEngine Instance;

	private static ProcessEngine processEngine;

	private final static String JBPM_JNDINAME = "java:/ProcessEngine";

	/**
	 * 
	 */
	private JbpmEngine() {
		try {
			InitialContext ctx = new InitialContext();
			JbpmEngine.processEngine = (ProcessEngine) ctx
					.lookup(JbpmEngine.JBPM_JNDINAME);

		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 
	 * @return
	 */
	public static final JbpmEngine getInstance() {
		if (Instance == null) {
			Instance = new JbpmEngine();
		}
		return Instance;
	}

	/**
	 * 
	 * @param file
	 * @return
	 */
	public String deployFromClasspath(String file) {

		System.out.println(JbpmEngine.processEngine.getRepositoryService()
				.createDeployment().addResourceFromClasspath(file).getId());

		return JbpmEngine.processEngine.getRepositoryService()
				.createDeployment().addResourceFromClasspath(file).deploy();
	}

	/**
	 * 
	 * @param key
	 */
	public ProcessInstance startByKey(String key) {
		return JbpmEngine.processEngine.get(ExecutionService.class)
				.startProcessInstanceByKey(key);
	}

	/**
	 * 
	 * @param key
	 * @param params
	 */
	public ProcessInstance startByKey(String key, Map<String, ?> params) {
		return JbpmEngine.processEngine.get(ExecutionService.class)
				.startProcessInstanceByKey(key, params);
	}
}
